package cn.itcast.mq.config;

import com.rabbitmq.client.ReturnCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware {
// Bean工厂的通知。当bean工厂准备好了以后，就会通知该类
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取RabbitTemplate对象
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 配置returnCallback
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            //  判断是不是一个延迟错误：
            if (message.getMessageProperties().getReceivedDelay() > 0) {
                // 如果说是一个延迟消息，那么忽略这个消息，返回空，不在报错
                return;
            }

            // 记录日志： 依次填写到占位符中。
            log.error("消息发送到队列失败, 响应码{} ，失败原因{}，交换机{} ，路由key{},消息:{}",replyCode,replyText,exchange
            ,routingKey,message);
        });

    }
}
